let id = window.localStorage.getItem('id');
let token = window.localStorage.getItem('token');
getLogin();
function getLogin() {
    if (!id || !token) window.location.href = './login.html';
    getCartList();
}

// 确认登录状态，获取购物车信息
async function getCartList() {
    let res = await pAjax({
        url: 'http://localhost:8888/cart/list',
        data: { id },
        headers: { authorization: token },
        dataType: 'json'
    })
    console.log(res);
    if (res.code !== 1) {
        window.location.href = './login.html';
        return;
    }
    bindHtml(res.cart)

}


// 渲染到页面
// 

let allGoods = document.querySelector('.allgoods')
// let cartList = document.querySelector('.cart-list');

function bindHtml(list) {
    console.log(list);
    let totalNum = 0, totalSelect = 0, totalPrice = 0;
    list.forEach(item => {
        // 被选中时is_select为true
        // console.log(item);
        // console.log(item.is_select);
        if (item.is_select) {
            totalNum += item.cart_number;
            console.log(item.cart_number);
            totalSelect++;
            totalPrice += item.cart_number * item.current_price;
            // console.log(totalSelect);
        }
    });


    let str = `
                <h4>全部商品
                    <span>${totalNum}件</span>
                </h4>
                <div class="cart-main">
                    <div class="cart-th clearfix">
                        <div>
                            <input type="checkbox"  class="selectAll" ${totalSelect === list.length ? 'checked' : ''}>全选</div>
                        <div class="">商品</div>
                        <div class="">单价（元）</div>
                        <div class="">数量</div>
                        <div class="">小计（元）</div>
                        <div class="">操作</div>
                    </div>
                    <div class="cart-title clearfix">
                        <h5 class="fl">京东自营</h5>
                        <div class="yunfei fr">
                            运费：￥6.00
                            <span>还差￥99.00免运费</span>
                        </div>
                    </div>
                    <div class="cart-item-list">
                        <div class="cart-body">
                            <div class="cart-list">
                            </div>
                        </div>
                    </div>
                </div>
    `;
    list.forEach(item => {
        str += `
    <ul class="goods-list yui3-g">
                                    <li class="yui3-u-3-8 pr">
                                        <input data-id=${item.goods_id} type="checkbox" class="good-checkbox" ${item.is_select ? 'checked' : ''}>
                                        <div class="good-item">
                                            <div class="item-img">
                                                <img src="${item.img_small_logo}">
                                            </div>
                                            <div class="item-msg">${item.title}</div>
                                        </div>
                                    </li>
                                    <li class="yui3-u-1-8">
                                        <span>颜色: 银色</span>
                                        <br>
                                        <span>处理器: Core I5</span>
                                        <br>
                                        <span>内存: 8GB</span>
                                        <br>
                                        <span>尺寸: 13.3英寸</span>
                                        <br>
                                    </li>
                                    <li class="yui3-u-1-8">
                                        <span class="price">￥${item.current_price}</span>
                                    </li>
                                    <li class="yui3-u-1-8">
                                        <div class="clearfix">
                                            <a href="javascript:;" class="increment mins" data-id=${item.goods_id}>-</a>
                                            <input autocomplete="off" type="text" value="${item.cart_number}" minnum="1" class="itxt" data-id=${item.goods_id}>
                                            <a href="javascript:;" class="increment plus" data-id=${item.goods_id}>+</a>
                                        </div>
                                        <div class="youhuo">有货</div>
                                    </li>
                                    <li class="yui3-u-1-8">
                                        <span class="sum">￥${(item.cart_number * item.current_price).toFixed(2)}</span>
                                    </li>
                                    <li class="yui3-u-1-8">
                                        <div class="del1">
                                            <a href="javascript:;" class="aDel" data-id=${item.goods_id}>删除</a>
                                        </div>
                                        <div>移到我的关注</div>
                                    </li>
                                </ul>
    `

    });
    str += `
                <div class="cart-tool clearfix">
                    <div class="money-box">
                        <div class="sumprice">
                            <div class="sumprice-top">
                            <button  class="clearAll" ${list.length === 0 ? 'disabled' : ''}>清空购物车</button>
                            <button class="delAll" ${totalSelect === 0 ? 'disabled' : ''}>删除所有已选中</button>
                                <span>
                                    已选择
                                    <strong>${totalNum}</strong> 件商品</span>
                                <span>
                                    <em>总价（不含运费）：</em>
                                    <i class="summoney">￥
                                        <span>${totalPrice.toFixed(2)}</span>
                                    </i>
                                </span>
                            </div>
                            <div class="sumprice-bottom">
                                已节省：￥20.00
                            </div>
                        </div>
                        <div class="sumbtn">
                            <a class="sum-btn" href="pay.html">结算</a>
                        </div>
                    </div>
                </div>
    `
    allGoods.innerHTML = str;

}


// 事件委托
allGoods.addEventListener('click', async e => {
    e = e || window.event;
    let target = e.target || e.srcElement;
    try { e.preventDefault() } catch (err) { e.returnValue = false };
    // 点击单选事件
    if (target.className === 'good-checkbox') {
        let goodsId = target.dataset.id - 0;
        console.log(goodsId);
        let res = await pAjax({
            url: 'http://localhost:8888/cart/select',
            method: 'post',
            data: { id, goodsId },
            dataType: 'json',
            headers: { authorization: token }
        });
        console.log(res);
        if (res.code === 1) getCartList()
    }


    // 删除一个商品
    if (target.className === 'aDel') {
        let goodsId = target.dataset.id - 0;
        console.log(goodsId);
        let res = await pAjax({
            url: 'http://localhost:8888/cart/remove',
            data: { id, goodsId },
            dataType: 'json',
            headers: { authorization: token }
        });
        console.log(res);
        if (res.code === 1) getCartList()
    }

    // 增加一件商品
    if(target.className === 'increment plus'){
        let goodsId = target.dataset.id - 0;
        let num = target.previousElementSibling.value - 0;
        let res = await pAjax({
            url : 'http://localhost:8888/cart/number',
            method : 'post',
            data : {id,goodsId,number : num + 1},
            dataType : 'json',
            headers: { authorization: token }
        })
        console.log(res);
        if(res.code === 1) getCartList()
    }


    // 减少一件商品
    if(target.className === 'increment mins'){
        let goodsId = target.dataset.id - 0;
        let num = target.nextElementSibling.value - 0;
        let res = await pAjax({
            url : 'http://localhost:8888/cart/number',
            method : 'post',
            data : {id,goodsId,number : num - 1},
            dataType : 'json',
            headers: { authorization: token }
        })
        console.log(res);
        if(res.code === 1) getCartList()
    }


    // 选择商品数量
    let itxt = document.querySelector('.itxt')
    console.log(itxt);
    itxt.addEventListener('input',async ()=>{
        
        if(target.className === 'itxt'){
            let goodsId = target.dataset.id - 0;
            let num = target.value - 0;
            
                let res = await pAjax({
                    url : 'http://localhost:8888/cart/number',
                    method : 'post',
                    data : {id,goodsId,number : num},
                    dataType : 'json',
                    headers: { authorization: token }
                })
                console.log(res);
            if(res.code === 1) getCartList()
        }    
    })

    // 全部选中
    if(target.className === 'selectAll') {
        // 全部选中需要一个type参数来获取选中状态，按钮选中的状态为true和false，如果选中true就为1，未选中false就为0
        let type = target.checked ? 1 : 0;
        let res = await pAjax({
            url : 'http://localhost:8888/cart/select/all',
            method : 'post',
            data : {id,type},
            dataType : 'json',
            headers: { authorization: token }
        })
        console.log(res);
        if(res.code === 1 ) getCartList()
    }

    //删除已选中
    if(target.className === 'delAll'){
        let res = await pAjax({
            url : 'http://localhost:8888/cart/remove/select',
            data : {id},
            dataType : 'json',
            headers: { authorization: token }
        })
        console.log(res);
        if(res.code === 1) getCartList();
    }

    // 清空购物车
    if(target.className === 'clearAll'){
        let res = await pAjax({
            url : 'http://localhost:8888/cart/clear',
            data : {id},
            dataType : 'json',
            headers: { authorization: token }
        })
        console.log(res);
        if(res.code === 1) getCartList();
    }
})